package main

import (
	"encoding/json"
	"fmt"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"os"
)

type Order struct {
	ID         string       `json:"id"`
	Name       string       `json:"name,omitempty"`
	Quantity   int          `json:"quantity"`
	TotalPrice float64      `json:"totalPrice"`
	Items      []*OrderItem `json:"items"`
}

type OrderItem struct {
	Id    string  `json:"id"`
	Name  string  `json:"name"`
	Price float64 `json:"price"`
}

func main() {

	fmt.Println("========解析json实例======")
	parseNLP()
	fmt.Println("========解析json======")
	unmarshal()

	fmt.Println("========格式化成json======")
	o := Order{
		ID:         "12134",
		Name:       "learn go",
		Quantity:   5,
		TotalPrice: 100,
		Items: []*OrderItem{
			{
				Id:    "123123",
				Name:  "慕课网",
				Price: 6800000,
			},
			{
				Id:    "564334",
				Name:  "图灵",
				Price: 67000,
			},
		},
	}

	items := make([]*OrderItem, 2)
	items[0] = &OrderItem{Id: "9002341", Name: "乒乓球", Price: 1}
	items[1] = &OrderItem{Id: "9002349", Name: "羽毛球", Price: 2}
	o2 := Order{
		ID:         "978545",
		Quantity:   1,
		TotalPrice: 88.5,
		Items:      items,
	}

	fmt.Printf("%+v \n", o)

	marshal, err := json.Marshal(o)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%s \n", marshal)

	marshal2, err := json.Marshal(o2)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%s \n", marshal2)
}

func unmarshal() {
	s := `{"id":"12134","name":"learn go","quantity":5,"totalPrice":100,"items":[{"id":"123123","name":"慕课网","price":6800000},{"id":"564334","name":"图灵","price":67000}]} `
	var o Order
	err := json.Unmarshal([]byte(s), &o)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%+v \n", o)
}

func parseNLP() {
	//LTAI5tKSAQ3NiHf91fwomzBq
	//gJtbcANqRXpnHzqiSjLjBVEnVA0MRZ
	AccessKeyId := os.Getenv("NLP_AK_ENV")
	AccessKeySecret := os.Getenv("NLP_SK_ENV")
	client, err := sdk.NewClientWithAccessKey("cn-hangzhou", AccessKeyId, AccessKeySecret)
	if err != nil {
		panic(err)
	}
	request := requests.NewCommonRequest()
	request.Domain = "alinlp.cn-hangzhou.aliyuncs.com"
	request.Version = "2020-06-29"
	// 因为是RPC接口，因此需指定ApiName(Action)
	request.ApiName = "GetWsChGeneral"
	request.QueryParams["ServiceCode"] = "alinlp"
	request.QueryParams["Text"] = "我是张同方"
	request.QueryParams["TokenizerId"] = "GENERAL_CHN"
	request.QueryParams["OutType"] = "1"
	response, err := client.ProcessCommonRequest(request)
	if err != nil {
		panic(err)
	}
	fmt.Println(response.GetHttpContentString())
}
